package com.chenqi.tool.ext

import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.MultipartBody
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.asRequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject
import java.io.File

/**
 * 作者: CQ
 * 日期: 2022-06-10
 * 说明:
 */

// 字符串转换成RequestBody
fun String.toRequestBody() : RequestBody {
    return this.toRequestBody("application/json;charset=UTF-8".toMediaTypeOrNull())
}

fun JSONObject.toRequestBody() : RequestBody {
    return this.toString().toRequestBody("application/json;charset=UTF-8".toMediaTypeOrNull())
}

fun String.toNullRequestBody() : RequestBody {
    return this.toRequestBody(null)
}

fun JSONArray.toRequestBody() : RequestBody {
    return this.toString().toRequestBody("application/json;charset=UTF-8".toMediaTypeOrNull())
}

/**
 * 上传带参数文件
 *  val body = newRequestBody(file, "file") {
 *                  put("watermark", "true")
 *             }
 */
inline fun newRequestBody(file : File, fileKey : String, params : MutableMap<String, String>.() -> Unit = {}) : RequestBody {
    val body = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    val part = MultipartBody.Part.createFormData(fileKey, file.name, body)
    val map = HashMap<String, String>().apply { params() }
    return MultipartBody.Builder().apply {
        addPart(part)
        map.forEach {
            addFormDataPart(it.key, it.value)
        }
    }.build()
}

inline fun newRequestBody(file : File, fileKey : String) : RequestBody {
    val body = file.asRequestBody("multipart/form-data".toMediaTypeOrNull())
    val part = MultipartBody.Part.createFormData(fileKey, file.name, body)
    return MultipartBody.Builder().apply {
        addPart(part)
    }.build()
}

// 半角转全角
fun String.toFullAngleFromHalf() : String {
    val c = this.toCharArray()
    for (i in c.indices) {
        val index = c[i].toInt()
        if (index == 32) {
            c[i] = 12288.toChar()
            continue
        }
        if (index < 127)
            c[i] = (c[i] + 65248)
    }
    return String(c)
}

